package ModelLayer;
import java.util.ArrayList;
import java.util.Iterator;
/**
 * Write a description of class LoanRecords here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class LoanRecords
{
    // instance variables - replace the example below with your own
    private ArrayList<Loan> loans;
    private static LoanRecords instance = null;

    /**
     * Constructor for objects of class LoanRecords
     */
    private LoanRecords()
    {
        // initialise instance variables
        loans = new ArrayList<Loan>();
    }

    public static LoanRecords getInstance()
    {
        if(instance == null)
        {
            instance = new LoanRecords();
        }

        return instance;
    }

    public ArrayList<Loan> getLoansList()
    {
        return loans;
    }

    public Loan getLoan(int id)
    {
        Loan theLoan = null;
        boolean found = false;
        Iterator<Loan> it = loans.iterator();
        while(it.hasNext() && !found)
        {
            Loan loan = it.next();
            if(loan.getId() == id)
            {
                theLoan = loan;
                found = true;
            }
        }        
        return theLoan;
    }

    public void removeLoan(int id)
    {        
        Loan loan = getLoan(id);
        if(loan != null)
        {
            loans.remove(loan);

        }
    }

    public void addLoan(Loan loan)
    {   
        loans.add(loan);
    }

    public void createLoan(int personID, int dvdNr, int copySerialNr, int loadID, long borrowDate, int borrowPeriod)
    {
        Loan loan = new Loan(personID, dvdNr, copySerialNr, loadID, borrowDate, borrowPeriod, "Borrowed");
        loan.getLoaner().setLoan(loan);
        loans.add(loan);
        DVDRecords.getInstance().getDVD(dvdNr).getCopy(copySerialNr).setSts("Borrowed");        
    }

    public void printAllLoan()
    {
        if (loans.size() !=0)
        {
            for(Loan loan : loans)
            {
                loan.printLoanInfo();
            }
        }
    }

    public void updateLoan(int choice, int id, String value)
    {
        Loan loan = getLoan(id);
        if (loan != null)
        {
            if(choice == 1)
            {
                loan.setBorrowDate(Long.parseLong(value));
            }
            if(choice == 2)
            {
                loan.setBorrowPeriod(Integer.parseInt(value));
            }
            if(choice == 3)
            {
                loan.setState(value);
            }

        }
    }
  
    
    
    public void returnLoan(int loanID, long returnDate)
    {
        Loan loan = getLoan(loanID);
        loan.returnState(returnDate);
    }

}
